﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class login : MonoBehaviour {

    public InputField mInputAccount;
    public InputField mInputPassword;

    #region U3D API

    void Start ( ) {
      
    }

    #endregion U3D API

    #region UGUI事件

    public void OnLogin ( ) {
        if (valid( )) {         
            GameSetting.Instance.Pid = mInputAccount.text;
            GameSetting.Instance.Password = mInputPassword.text;           
            // 登录请求
            NetHandle.Instance.LoginReq(LoginReturn);
        }
    }

    public void OnRegister ( ) {
        NetHandle.Instance.RegisterReq(RegisReturn);
    }

    #endregion UGUI事件

    #region 服务器回调

    private void LoginReturn (ActionResult actionResult) {
        if (actionResult != null) {
            PlayerPrefs.SetString("UserName", mInputAccount.text);
            PlayerPrefs.SetString("Password", mInputPassword.text);
            // 握手请求
            NetHandle.Instance.HelloAction(0);        

            if (actionResult.Get<int>("GuideID") == (int)ActionType.CreateRote) {
                // 登陆返回未创建角色。需要跳转创建角色            
                Application.LoadLevel("CreateRote");
            } else {
                Debug.Log("UserID = " + actionResult.Get<string>("UserID"));
                Debug.Log("GuideID = " + actionResult.Get<int>("GuideID"));                     
                Application.LoadLevel("CreateRote");
            }
        } else {
            actionResultError( );     
        }
    }

    private void RegisReturn (ActionResult actionResult) {
        if (actionResult == null) {
            actionResultError( );     
            return;
        } 
        Debug.Log("一键注册成功!账号:" + actionResult.Get<string>("passportID") + "  密码：" + actionResult.Get<string>("password"));
        mInputAccount.text = actionResult.Get<string>("passportID");
        mInputPassword.text = actionResult.Get<string>("password");
    }

    #endregion 服务器回调
    
    // InputField valid
    bool valid ( ) {
        if (mInputAccount.text == "" || mInputPassword.text == "") {
            Debug.LogError("请输入账号和密码！");
            return false;
        }
        return true;
    }

    private void actionResultError ( ) {
        Debug.LogError("actionResult is null");           
    }

}
